package com.collect.zambia.zhiUtils;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by gsj on 2018/10/19.
 */

public class CryptoUtil {
    /**
     * 将参数key，进行sha256加密，然后转换成16进制的表示形式。
     *
     * @param text
     * @return
     */
    public static String sha256(String text) {
        return digest(text, "SHA-256");
    }

    /**
     * 将参数key，进行MD5加密，然后转换成16进制的表示形式。
     *
     * @param text
     * @return
     */
    public static String md5(String text) {
        return digest(text, "MD5");
    }

    private static String digest(String text, String method) {
        String retVal;
        try {
            MessageDigest mDigest = MessageDigest.getInstance(method);
            mDigest.update(text.getBytes());
            retVal = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            retVal = String.valueOf(text.hashCode());
        }
        return retVal;
    }

    /**
     * 将字节数组转换成16进制的字符串。
     *
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) {
        // http://stackoverflow.com/questions/332079
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    private static final String HASH_ALGORITHM = "HmacSHA256";

    public static String hmac(String text, String secret)throws SignatureException {
        try{
            Key sk = new SecretKeySpec(secret.getBytes(), HASH_ALGORITHM);
            Mac mac = Mac.getInstance(sk.getAlgorithm());
            mac.init(sk);
            final byte[] hmac = mac.doFinal(text.getBytes());
            StringBuilder sb = new StringBuilder(hmac.length * 2);

            @SuppressWarnings("resource")
            Formatter formatter = new Formatter(sb);
            for (byte b : hmac) {
                formatter.format("%02x", b);
            }

            return sb.toString();
        }catch (NoSuchAlgorithmException e1){
            throw new SignatureException("error building signature, no such algorithm in device "+ HASH_ALGORITHM);
        }catch (InvalidKeyException e){
            throw new SignatureException("error building signature, invalid key " + HASH_ALGORITHM);
        }
    }
}
